//
//  HttpTool.m
//  网络请求封装
//
//  Created by apple on 15-8-20.
//  Copyright (c) 2015年 jackyu
//

#import "HttpTool.h"
#import "AFNetworking.h"
//#import "NSDictionary+MD5.h"
//#import "StringConvert.h"
//#import "AppDelegate.h"
//#import "UUID.h"
#import "MMZCViewController.h"

@implementation HttpTool

+ (void)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    // 1.获得请求管理者
    static AFHTTPSessionManager *mgr = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mgr = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:kBaseUrl]];
    });
    [mgr.requestSerializer setValue:[MySingleton sharedMySingleton].tokenID forHTTPHeaderField:@"access_token"];

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    // 2.发送GET请求
    [mgr GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
//            success(responseObject);
            if (![responseObject[@"message"] isEqualToString:@"服务端异常"]) {
                success(responseObject);
            }
            else
            {
                [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:NO];
            }
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSString* err=[error localizedDescription];
        if ([err containsString:@"401"]) {
            [HttpTool post1:[NSString stringWithFormat:@"auth/oauth/token?grant_type=refresh_token&refresh_token=%@",[MySingleton sharedMySingleton].refreshToken] params:nil success:^(id responseObj) {
                NSLog(@"");
                [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
                //        rootViewController = nav;
            } failure:^(NSError *error) {
                //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
                //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
                
                [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
                
            }];
        }
        if (failure) {
            failure(error);
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            //客户提的bug，出现加载失败，应该是无网络下出现的
//            [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"加载失败，稍后再试" withTime:1.0];
        }
    }];
}

+ (void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    // 1.获得请求管理者
//    AFHTTPSessionManager *mgr = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:kBaseUrl]];
    static AFHTTPSessionManager *mgr = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mgr = [AFHTTPSessionManager manager];
        
        mgr.requestSerializer = [AFJSONRequestSerializer serializer];
        mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json", @"text/plain", @"text/javascript", nil];
        mgr.requestSerializer.timeoutInterval = 10;
//        [mgr.requestSerializer setValue:[MySingleton sharedMySingleton].tokenID forHTTPHeaderField:@"access_token"];
    });
    [mgr.requestSerializer setValue:[MySingleton sharedMySingleton].tokenID forHTTPHeaderField:@"access_token"];

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //secret
    NSMutableDictionary *newdic = [NSMutableDictionary dictionaryWithDictionary:params];
//    [newdic setValue:[NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]] forKey:@"timestamp"];
//    [newdic setValue:[newdic secretDictionary] forKey:@"sign"];
//    [newdic setValue:@"password" forKey:@"grant_type"];
//    [newdic setValue:@"1" forKey:@"issign"];
//    [newdic setValue:[UserInfo share].version forKey:@"appversion"];
//    [newdic setValue:@"0" forKey:@"uasystem"];
//    [newdic setValue:[UserInfo share].phoneModel forKey:@"devicetype"];
//    [newdic setValue:[UserInfo share].uid forKey:@"operuid"];
//    [newdic setValue:[UUID getUUID] forKey:@"deviceid"];
    // 2.发送POST请求
    [mgr POST:[NSString stringWithFormat:@"%@/%@", kBaseUrl, url] parameters:newdic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            if (![responseObject[@"message"] isEqualToString:@"服务端异常"]) {
            success(responseObject);
            }
            else
            {
                [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:NO];
            }
//            if (responseObject[@"token"]) {
//                success(responseObject);
//            }
//            if ([responseObject[@"result"] isEqualToString:@"0"]) {
//                success(responseObject);
//            }else {
//                [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:NO];
//                [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:responseObject[@"errmsg"] withTime:1.0];
//            }
//
//            if ([responseObject[@"errcode"] isEqualToString:@"100024"] || [responseObject[@"errcode"] isEqualToString:@"100025"]) {
//                [UserInfo share].loginState = NO;
//
//                [(AppDelegate *)[UIApplication sharedApplication].delegate setupRootVC];
//                [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:responseObject[@"errmsg"] withTime:2.0];
//
//                [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
//            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSString* err=[error localizedDescription];
        if ([err containsString:@"401"]) {
            [HttpTool post1:[NSString stringWithFormat:@"auth/oauth/token?grant_type=refresh_token&refresh_token=%@",[MySingleton sharedMySingleton].refreshToken] params:nil success:^(id responseObj) {
                NSLog(@"");
                [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
                //        rootViewController = nav;
            } failure:^(NSError *error) {
                //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
                //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
                
                [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
                
            }];
        }
        if (failure) {
            failure(error);
//            [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"加载失败，稍后再试" withTime:1.0];
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        }
    }];
}

//刷新token请求
+ (void)post1:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    // 2.发送POST请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSMutableDictionary *mutableParameters = [NSMutableDictionary new];
    [mutableParameters setObject:@"clientTest" forKey:@"client_id"];
    [mutableParameters setValue:@"123456" forKey:@"client_secret"];
    [mutableParameters setValue:@"refresh_token" forKey:@"grant_type"];
    [mutableParameters setValue:[MySingleton sharedMySingleton].refreshToken forKey:@"refresh_token"];

    NSDictionary* param = [NSDictionary dictionaryWithDictionary:mutableParameters];

    [manager POST:[NSString stringWithFormat:@"%@/%@",kBaseUrl,@"auth/oauth/token"] parameters:param success:^(NSURLSessionTask *task, id responseObject) {
        [MySingleton sharedMySingleton].tokenID=[responseObject objectForKey:@"access_token"];
        [MySingleton sharedMySingleton].refreshToken=[responseObject objectForKey:@"refresh_token"];
        NSString* b=[responseObject objectForKey:@"access_token"];
        
        NSLog(@"");
        //本地存token
        NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
        [defaults2 setObject:[responseObject objectForKey:@"access_token"] forKey:@"accessToken"];
        [defaults2 setObject:[responseObject objectForKey:@"refresh_token"] forKey:@"refreshToken"];
        [defaults2 synchronize];
        //发送通知
        NSNotification * noti = [NSNotification notificationWithName:@"noti" object:nil userInfo:@{@"message":@"HelloWorld"}];
        //发送通知
        [[NSNotificationCenter defaultCenter]postNotification:noti];
        NSNotification * notiSync = [NSNotification notificationWithName:@"notiSync" object:nil userInfo:@{@"message":@"HelloWorld"}];
        //发送通知
        [[NSNotificationCenter defaultCenter]postNotification:notiSync];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSString* err=[error localizedDescription];
        if (failure) {
            failure(error);
            //            [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"加载失败，稍后再试" withTime:1.0];
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        }
        //400跳转首页
        if ([err containsString:@"400"]) {
            MMZCViewController * homeVC = [[MMZCViewController alloc]init];
            RTRootNavigationController *nav = [[RTRootNavigationController alloc] initWithRootViewController:homeVC];
            // 添加为子控制器
            nav.title = @"任务箱";
            [UIApplication sharedApplication].delegate.window.rootViewController=nav;
        }
    }];
}
@end
